﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Diagnostics;

namespace WordToHtml
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dr = folderBrowserDialog1.ShowDialog();
                this.textBox1.Text = "";
                if (dr == System.Windows.Forms.DialogResult.OK)
                {
                    this.textBox1.Text = this.folderBrowserDialog1.SelectedPath;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Faild!:\r\n Message:" + ex.Message);
            }
        }

        /// <summary>
        /// 生成项目文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            FrmGenerate frm = new FrmGenerate(this.textBox1.Text, true);
            this.Hide();
            frm.ShowDialog();
            this.Show();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                Convert();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Convert()
        {
            if (!String.IsNullOrEmpty(this.textBox1.Text) && Directory.Exists(this.textBox1.Text))
            {
                string[] strs = Directory.GetDirectories(this.textBox1.Text);

                for (int i = 0; i < strs.Length; i++)
                {
                    Exec(strs[i]);
                }
                MessageBox.Show("Success!");
                if (MessageBox.Show("是否继续生成项目文件", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    FrmGenerate frm = new FrmGenerate(this.textBox1.Text);
                    this.Hide();
                    frm.ShowDialog();
                    this.Show();
                }
            }
        }

        private void Exec(string childPath)
        {
            string[] array = Directory.GetFiles(childPath);

            //排序文件
            array = (from item in array orderby item ascending select item).ToArray();

            if (array.Length > 0)
            {

                //生成txt
                //CreateFilePathContent(this.textBox1.Text, "dict_init");
                CreateFilePathContent(childPath + "\\dict.txt", array);

                #region 修改名称
                for (int i = 0; i < array.Length; i++)
                {
                    string sourceWordFilePath = array[i];
                    string wordFilePath1 = childPath + @"\" + string.Format("({0}).docx", i + 1);
                    string wordFilePath2 = childPath + @"\" + string.Format("({0}).doc", i + 1);
                    if (sourceWordFilePath.EndsWith(".docx"))
                    {
                        File.Copy(array[i], wordFilePath1);
                    }
                    else if (sourceWordFilePath.EndsWith(".doc"))
                    {
                        File.Copy(array[i], wordFilePath2);
                    }
                    File.Delete(array[i]);
                }
                #endregion

                #region 文件夹
                DirectoryInfo di = Directory.CreateDirectory(childPath + @"\htmlFiles");
                #endregion

                //生成html
                WordToHtml.CreateWordToHtmlFile(childPath, di.FullName);

                //压缩文件
                CreateRar("\"" + childPath + "\\html.zip\"", "\"" + di.FullName + "\\\"");
            }
        }

        private void CreateFilePathContent(string path, string[] array)
        {
            using (TextWriter tw = File.AppendText(path))
            {
                for (int i = 0; i < array.Length; i++)
                {
                    string str = array[i].Substring(array[i].LastIndexOf(@"\") + 1, array[i].LastIndexOf(@".") - array[i].LastIndexOf(@"\") - 1);
                    tw.WriteLine("●" + str);
                }
                tw.Close();
            }
        }

        private void CreateFilePathContent(string filePath, string name)
        {

            //Process p = new Process();
            //p.StartInfo.FileName = "cmd.exe";
            //p.StartInfo.UseShellExecute = false;
            //p.StartInfo.RedirectStandardInput = true;
            //p.StartInfo.RedirectStandardOutput = true;
            //p.StartInfo.CreateNoWindow = true;
            //p.Start();
            //p.StandardInput.WriteLine("cd " + filePath);
            //p.StandardInput.WriteLine(filePath.Substring(0, filePath.IndexOf(":") + 1));
            //p.StandardInput.WriteLine(@"dir /on >" + name + ".txt");
            //p.StandardInput.WriteLine("exit");
            //p.WaitForExit();
            //string str = p.StandardOutput.ReadToEnd();
            ////Response.Write(str); 
            //p.Close();


        }

        /// <summary>
        /// 生成压缩文件
        /// </summary>
        /// <param name="rarName">目标文件</param>
        /// <param name="path">源文件</param>
        /// <returns></returns>
        private bool CreateRar(string rarName, string path)
        {
            Process winrar = new Process();
            winrar.StartInfo.FileName = "winrar.exe";
            winrar.StartInfo.CreateNoWindow = true;
            winrar.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            winrar.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
            winrar.StartInfo.Arguments = string.Format("a {0} {1} -r -ep1", rarName, path);
            winrar.Start();
            winrar.WaitForExit();
            if (winrar.HasExited)
            {
                int iExitCode = winrar.ExitCode;
                if (iExitCode == 0)
                {
                    //正常完成  
                    return true;
                }
                else
                {
                    //有错  
                    return false;
                }
            }
            winrar.Close();
            return false;
        }


        private void UpTxt(string path)
        {
            string ansiFilepath = path + "\\dict_init.txt";
            string unicodeFilePath = path + "\\dict.txt";

            // convert DBCS-932 encoded file to unicode-file 
            using (StreamReader sr = new StreamReader(ansiFilepath, Encoding.Default, false))
            {
                using (StreamWriter sw = new StreamWriter(unicodeFilePath, false, Encoding.UTF8))
                {
                    sw.Write(sr.ReadToEnd());
                }
            }

            File.Delete(ansiFilepath);
        }
    }
}
